import {deepFullCopy, messages} from 'share/common';
import React, { Component, PropTypes } from 'react'
import { Spin, Dropdown, Menu, Icon } from 'antd';
import expenseReportService from "containers/expense-report/expense-report.service";
import SlideExpenseReportDetailExpenseList from './slide-expense-report-detail-expense-list'
import SlideExpenseReportDetailExpenseCalendar from './slide-expense-report-detail-expense-calendar'
import SlideExpenseReportDetailExpenseFile from './slide-expense-report-detail-expense-file'
import SlideExpenseReportDetailExpenseInvoiceSummary from './slide-expense-report-detail-expense-invoice-summary'
import Condition from "components/condition";

const { If } = Condition;

class SlideExpenseReportDetailExpense extends Component {

  state = {
    costCenterItemsApportion: [],
    invoiceData: {
      invoiceGroups: [],
      expenseReportInvoices: []
    },
    loading: true,
    mode: localStorage.getItem("finance-view-invoice-mode") || 'classify',
    filterCondition: {
      owner: [],
      ownerOID: [],
      expenseType: [],
      expenseTypeOID: [],
      date: []
    },
    currentViewExpenseList: [],
    receiptList: []
  };

  static contextTypes = {
    info: PropTypes.object,
    jobInfo: PropTypes.object,
    ocrEnabled: PropTypes.bool,
    readOnly: PropTypes.bool
  };

  componentDidMount() {
    this.getExpenseList();
    this.getCostCenterItems();
    this.getItineraryList();
  }

  getExpenseList = ( needRefresh = true ) => {
    if(needRefresh) {
      const { info: { expenseReportOID } } = this.context;
      this.setState({ loading: true });
      let params = {
        expenseReportOID,
        financeQuery: 'Y',
        isDateCombinedUTC: false
      };
      return expenseReportService.getExpenseAccountInfo(params)
        .then(res => {
          const { onGetInvoice } = this.props;
          this.setState({ invoiceData: res.data.rows });
          this.getReceiptList(res.data.rows);
          onGetInvoice(res.data.rows.expenseReportInvoices);
        })
        .finally(() => {
          this.setState({ loading: false })
        })
    }
  };

  getCostCenterItems() {
    const { info: { custFormValues } } = this.context;
    let costCenterItemsApportion = [];
    //查询是否多币种、初始化成本中心项
    custFormValues.map(field => {
      if (field.messageKey === 'select_cost_center') {
        if (JSON.parse(field.fieldConstraint || '{}').isApportionItem) { //参与分摊
          costCenterItemsApportion.push({
            fieldName: field.fieldName,
            costCenterOID: JSON.parse(field.dataSource || '{}').costCenterOID,
            costCenterItemName: field.showValue,
            name: field.showValue,
            costCenterItemOID: field.value,
            required: field.required
          })
        }
      }
      if (field.messageKey === 'select_department') {
        if (JSON.parse(field.fieldConstraint || '{}').isApportionItem) { //参与分摊
          costCenterItemsApportion.push({
            fieldName: field.fieldName,
            costCenterOID: '00000000-0000-0000-0000-000000000000',
            costCenterItemName: field.showValue,
            name: field.showValue,
            costCenterItemOID: field.value,
            required: field.required
          })
        }
      }
    });
    this.setState({ costCenterItemsApportion });
  }

  // 获取行程信息
  getItineraryList = () => {
    const {info: {expenseReportOID}} = this.context;
    expenseReportService.getItineraryList({expenseReportOID, isItineraryMode: true})
      .then(res => {
        let expenseReportItineraryDTOList = this.getCurrentObjValue(res.data, 'expenseReportItineraryDTOList') || [];
        let modeMap = this.modeMap;
        let currentViewExpenseList = [];
        if (expenseReportItineraryDTOList.length > 0) {
          modeMap.itinerary = messages('expense-14.key523')/*行程模式*/;
          currentViewExpenseList = this.initCurrentViewExpenseList(res.data);
        }
        this.setState({
          currentViewExpenseList,
          modeMap
        });
      });
  };
  initCurrentViewExpenseList = (itineraryInfo) => {
    // 其他模式下显示费用信息处理 这个是使用之前的 不许操作处理
    let result = [];
    // 行程模式处理 行程模式显示需要将行程信息添加进数据 且行程信息需要合并列 这里处理数据源信息 需要自己处理结构
    const sourceItineraryInfo = deepFullCopy(itineraryInfo);
    // 这个值一定存在 所以不需要判断
    sourceItineraryInfo.expenseReportItineraryDTOList.forEach((item, index) => {
      result.push({
        label: messages('expense-14.key524',{arg1: index+1})/*行程{arg1}*/,
        invoiceOID: `web-itinerary-${index+1}`,
        webShowMod: 'itinerary',
        startDate: item.startDate,
        endDate: item.endDate,
        dpCityName: item.dpCityName,
        cityName: item.cityName,
        remark: item.remark,
        userDTOList: item.userDTOList,
      });
      if (this.getCurrentObjValue(item, 'invoiceViewDTOList.length') > 0) {
        result.push(...item.invoiceViewDTOList.map((invoice, index) => {
          invoice.webShowSequence = index + 1;
          return invoice;
        }));
      }
    });
    // 其他费用
    let otherInvoiceList = this.getCurrentObjValue(sourceItineraryInfo, 'otherInvoiceList') || [];
    if (otherInvoiceList.length > 0) {
      result.push({
        label: messages('expense-14.key525')/*其他*/,
        message: messages('expense-14.key526')/*费用消费日期没有匹配到行程日期的费用*/,
        invoiceOID: `web-other-invoice`,
        webShowMod: 'otherInvoice',
      });
      result.push(...otherInvoiceList.map((invoice, index) => {
        invoice.webShowSequence = index + 1;
        return invoice;
      }));
    }
    return result;
  };

  getReceiptList = invoiceData => {
    let receiptList = [];
    invoiceData.expenseReportInvoices.map(invoice => {
      receiptList = receiptList.concat(invoice.invoiceView.receiptList);
    });
    this.setState({ receiptList });
  };

  onChangeMode = e => {
    let mode = typeof e === 'string' ? e : e.key;
    this.setState({ mode });
    if (mode !== 'itinerary') {
      localStorage.setItem("finance-view-invoice-mode", mode);
    }
  };

  filterData = filterCondition => this.setState({
    filterCondition: filterCondition === null ? {
      owner: [],
      ownerOID: [],
      expenseType: [],
      expenseTypeOID: [],
      date: []
    } : filterCondition,
    mode: 'classify'
  });

  modeMap = {
    classify: messages('expense-14.key285')/*大类模式*/,
    normal: messages('expense-14.key286')/*普通模式*/,
    calendar: messages('expense-14.key287')/*日历模式*/,
  };
  render() {
    const { loading, invoiceData, costCenterItemsApportion, mode, filterCondition, currentViewExpenseList,
      receiptList } = this.state;
    const { onSelectExpense, onClickCollapse, tableLoading, afterSave, selectedExpense, activeTab } = this.props;
    const { expenseReportInvoices } = invoiceData || {};
    const menu = <Menu onClick={this.onChangeMode}>
      {Object.keys(this.modeMap)
        .map(key => <Menu.Item key={key}>{this.modeMap[key]}</Menu.Item>)}
    </Menu>;
    return (
      <div className='slide-expense-report-detail-expense'>
        <Dropdown
          overlay={menu}
          getPopupContainer={triggerNode => triggerNode.parentNode}
        >
          <span className='slide-expense-report-detail-expense-mode'>
             {this.modeMap[mode]}<Icon type="down" style={{ marginLeft: 5 }}/>
          </span>
        </Dropdown>
        <SlideExpenseReportDetailExpenseFile
          receiptList={receiptList}
          invoiceData={invoiceData}
          afterClose={this.getExpenseList}
        />
        <SlideExpenseReportDetailExpenseInvoiceSummary
          receiptList={receiptList}
          afterClose={this.getExpenseList}
        />
        <Spin spinning={loading}>
          {(['itinerary', 'classify', 'normal'].includes(mode)) && expenseReportInvoices && expenseReportInvoices.length > 0 &&
          <SlideExpenseReportDetailExpenseList
            activeTab={activeTab}
            invoiceData={invoiceData}
            filterCondition={filterCondition}
            costCenterItemsApportion={costCenterItemsApportion}
            getExpenseList={this.getExpenseList}
            currentViewExpenseList={currentViewExpenseList}
            getReportInfo={afterSave}
            onSelectExpense={onSelectExpense}
            filterData={this.filterData}
            onClickCollapse={onClickCollapse}
            tableLoading={tableLoading}
            mode={mode}
            selectedExpense={selectedExpense}
            goBack={this.props.goBack}
          />}
          {mode === 'calendar' && expenseReportInvoices && expenseReportInvoices.length > 0 &&
          <SlideExpenseReportDetailExpenseCalendar
            invoiceData={invoiceData}
            toggleMode={() => this.onChangeMode('classify')}
            filterData={this.filterData}
          />}
        </Spin>
      </div>
    )
  }

}

export default SlideExpenseReportDetailExpense;
